#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re, collections,codecs,inspect,sys

class Revisar:

	def __init__(self,word):
		self.word = word
		#Se abre el Diccionario.txt en Unicode
		self.text = codecs.open('Diccionario.txt',encoding='latin1').read()
		self.features = Revisar.words(self,self.text)
		self.NWORDS = Revisar.train(self,self.features)
		self.alphabet = 'abcdefghijklmnopqrstuvwxyz'

	def words(self,*args):
		#En la expresión regular estoy incluyendo todas las palabras,
		#la expresión regular original era [a-z]+ 
		return re.findall('\w+',self.text.lower(), re.U) 

	def train(self,*args):
		model = collections.defaultdict(lambda: 1)
		for f in self.features:
			model[f] += 1
		return model

	def edits1(self,*args):
		splits     = [(self.word[:i], self.word[i:]) for i in range(len(self.word) + 1)]
		deletes    = [a + b[1:] for a, b in splits if b]
		transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]	
		replaces   = [a + c + b[1:] for a, b in splits for c in self.alphabet if b]
		inserts    = [a + c + b     for a, b in splits for c in self.alphabet]
		return set(deletes + transposes + replaces + inserts)

	def known_edits2(self,*args):
		return set(e2 for e1 in Revisar.edits1(self,self.word) for e2 in Revisar.edits1(self,e1) if e2 in self.NWORDS)
	
	def known(self,words): 
		return set(w for w in words if w in self.NWORDS)
	
	def correct(self,*args):
		candidates = Revisar.known(self,[self.word]) or Revisar.known(self,Revisar.edits1(self)) or Revisar.known_edits2(self) or [self.word]
		return max(candidates, key = self.NWORDS.get)

	def main(self,*args):
		Revisar.correct(self)

if __name__=="__main__":
	app = Revisar()
	app.main()
